<template>
	<view class="bankcard-page">
		<!-- 头部导航 -->
		<!-- <view class="header">
			<view class="back-btn" @click="goBack">
				<image src="/static/img/icon-Get-into@3.png" class="back-icon"></image>
			</view>
			<view class="title">银行卡</view>
		</view> -->

		<!-- 银行卡列表 -->
		<view class="wrapper">
			<view class="cardbox">
				<!-- 银行卡项 -->
				<view v-for="card in cardList" :key="card.id" class="card">
					<view class="bankcards">
						<image :src="serverAddress + 'img/icon-gsyh@3x.png'" class="card-bg"></image>
						<view class="banktext">
							<view class="bank-name">{{ card.bank_name }}</view>
							<view class="card-number">{{ formatCardNumber(card.card_num) }}</view>
						</view>
						<view class="untie" @click="showUnbindDialog(card.id)">解 绑</view>
					</view>
				</view>

				<!-- 添加银行卡按钮 -->
				<view v-if="!cardList.length" class="btns" @click="addBankCard">
					<image :src="serverAddress + 'img/icon-tj@3x.png'" class="add-icon"></image>
					添加还款银行卡
				</view>
			</view>
			<view class="tip">目前只能添加一张</view>
		</view>

		<!-- 支付密码验证弹窗 -->
		<u-popup 
			v-model:show="showPayDialog" 
			mode="bottom" 
			width="600rpx" 
			height="400rpx"
			border-radius="20"
			closeable
			@close="hidePayDialog"
		>
			<view class="pay-dialog-content">
				<view class="pay-dialog-title">{{ payDialogTitle }}</view>
				<view class="pay-dialog-body">
					<view class="pay-tip">{{ payTip }}</view>
					<input 
						v-model="payPassword" 
						type="password" 
						maxlength="6" 
						:focus="showPayDialog"
						@input="onPasswordInput"
						placeholder="请输入6位数字密码"
						border="bottom"
						input-align="center"
						font-size="32"
					/>
				</view>
			</view>
		</u-popup>

		<!-- 解绑确认弹窗 -->
		<u-modal 
			:show="showUnbindModal" 
			title="温馨提示" 
			content="确认要解绑银行卡吗？解绑后将无法提现到该银行卡上"
			show-cancel-button
			confirm-text="确认"
			cancel-text="取消"
			@confirm="confirmUnbind"
			@cancel="cancelUnbind"
		></u-modal>
	</view>
</template>

<script>
import { walletApi, commonApi } from '@/api/index.js'
import md5 from '@/utils/md5.js'
import {
		inject
	} from 'vue'
export default {
	data() {
		return {
			serverAddress: inject('$serverAddress', ''),
			cardList: [],
			showPayDialog: false,
			showUnbindModal: false,
			payPassword: '',
			payDialogTitle: '检验支付密码',
			payTip: '请输入支付密码',
			isSettingPassword: false,
			firstPassword: '',
			secondPassword: '',
			currentUnbindId: null,
			payCallback: null
		}
	},
	
	onLoad() {
		
	},
	onShow() {
		this.loadBankCards()
	},
	
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载银行卡列表
		async loadBankCards() {
			try {
				const res = await walletApi.getBankCardList()
				if (res.r === 0) {
					this.cardList = res.data.list || []
				} else {
					uni.showToast({
						title: res.msg || '获取银行卡列表失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('获取银行卡列表失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 格式化银行卡号（显示后四位）
		formatCardNumber(cardNum) {
			if (!cardNum) return ''
			const len = cardNum.length
			return '*'.repeat(len - 4) + cardNum.slice(-4)
		},
		
		// 添加银行卡
		addBankCard() {
			this.showPayPasswordDialog(() => {
				// 支付密码验证成功后的回调
				const pages = getCurrentPages()
				const currentPage = pages[pages.length - 1]
				const options = currentPage.options
				
				if (options.nextpage) {
					uni.navigateTo({
						url: decodeURIComponent(options.nextpage)
					})
				} else {
					uni.navigateTo({
						url: '/pages/my/addbankcard'
					})
				}
			})
		},
		
		// 显示解绑确认弹窗
		showUnbindDialog(cardId) {
			this.currentUnbindId = cardId
			this.showUnbindModal = true
			console.log('========unbind=========')
		},
		
		// 确认解绑
		confirmUnbind() {
			this.showUnbindModal = false
			this.showPayPasswordDialog(() => {
				this.unbindBankCard(this.currentUnbindId)
			})
		},
		
		// 取消解绑
		cancelUnbind() {
			this.currentUnbindId = null
			this.showUnbindModal = false
		},
		
		// 解绑银行卡
		async unbindBankCard(cardId) {
			try {
				const res = await walletApi.deleteBankCard(cardId)
				if (res.r === 0) {
					uni.showToast({
						title: '解绑成功',
						icon: 'success'
					})
					this.loadBankCards() // 重新加载列表
				} else {
					uni.showToast({
						title: res.msg || '解绑失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('解绑银行卡失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			}
		},
		
		// 显示支付密码验证弹窗
		async showPayPasswordDialog(callback) {
			this.payCallback = callback
			this.resetPasswordState()
			
			try {
				// 检查是否已设置支付密码
				const res = await commonApi.checkPayPassword()
				if (res.data.is_set === 1) {
					this.payDialogTitle = '请输入支付密码'
					this.payTip = '请输入支付密码'
					this.isSettingPassword = false
				} else {
					this.payDialogTitle = '设置支付密码'
					this.payTip = '请设置支付密码'
					this.isSettingPassword = true
				}
				this.showPayDialog = true
			} catch (error) {
				console.error('检查支付密码状态失败:', error)
			}
		},
		
		// 隐藏支付密码弹窗
		hidePayDialog() {
			this.showPayDialog = false
			this.resetPasswordState()
		},
		
		// 重置密码状态
		resetPasswordState() {
			this.payPassword = ''
			this.firstPassword = ''
			this.secondPassword = ''
		},
		
		// 密码输入处理
		async onPasswordInput() {
			console.log('=================',this.isSettingPassword)
			if (this.payPassword.length < 6) return
			
			// 验证是否为6位数字
			if (!/^\d{6}$/.test(this.payPassword)) {
				uni.showToast({
					title: '支付密码由六位数字组成',
					icon: 'none'
				})
				this.payPassword = ''
				return
			}
			console.log('=================',this.isSettingPassword)
			if (this.isSettingPassword) {
				await this.handleSetPassword()
			} else {
				await this.handleVerifyPassword()
			}
		},
		
		// 处理设置密码
		async handleSetPassword() {
			if (!this.firstPassword) {
				// 第一次输入
				this.firstPassword = this.payPassword
				this.payPassword = ''
				this.payTip = '请再次输入支付密码'
			} else {
				// 第二次输入
				this.secondPassword = this.payPassword
				
				if (this.firstPassword !== this.secondPassword) {
					uni.showToast({
						title: '两次密码输入不一致',
						icon: 'none'
					})
					this.secondPassword = ''
					this.payPassword = ''
					return
				}
				
				// 调用设置密码接口
				try {
					const res = await commonApi.setPayPassword({
						pay_pwd: md5(this.firstPassword),
						pay_confirm_pwd: md5(this.secondPassword)
					})
					
					if (res.r === 0) {
						uni.showToast({
							title: '支付密码设置成功',
							icon: 'success'
						})
						this.hidePayDialog()
						if (this.payCallback) {
							this.payCallback()
						}
					} else {
						uni.showToast({
							title: res.msg || '设置失败',
							icon: 'none'
						})
						this.payPassword = ''
					}
				} catch (error) {
					console.error('设置支付密码失败:', error)
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
					this.payPassword = ''
				}
			}
		},
		
		// 处理验证密码
		async handleVerifyPassword() {
			try {
				const res = await commonApi.verifyPayPassword({
					pay_pwd: md5(this.payPassword)
				})
				
				if (res.r === 0) {
					this.hidePayDialog()
					if (this.payCallback) {
						this.payCallback()
					}
				} else {
					uni.showToast({
						title: res.msg || '密码错误',
						icon: 'none'
					})
					this.payPassword = ''
				}
			} catch (error) {
				console.error('验证支付密码失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
				this.payPassword = ''
			}
		}
	}
}
</script>

<style scoped>
.bankcard-page {
	min-height: 100vh;
	background-color: #eeeeee;
}

.header {
	display: flex;
	align-items: center;
	height: 88rpx;
	background-color: #fff;
	position: relative;
}

.back-btn {
	position: absolute;
	left: 30rpx;
	width: 40rpx;
	height: 40rpx;
}

.back-icon {
	width: 100%;
	height: 100%;
}

.title {
	flex: 1;
	text-align: center;
	font-size: 36rpx;
	color: #333;
}

.wrapper {
	padding-top: 20rpx;
}

.cardbox {
	background-color: #fff;
	padding: 50rpx 0;
}

.card {
	text-align: center;
	margin-bottom: 30rpx;
}

.bankcards {
	width: 666rpx;
	height: 170rpx;
	margin: 0 auto;
	position: relative;
}

.card-bg {
	width: 100%;
	height: 100%;
	position: absolute;
	left: 0;
	top: 0;
	z-index: 1;
}

.banktext {
	position: absolute;
	left: 166rpx;
	top: 20rpx;
	z-index: 2;
	color: #fff;
}

.bank-name {
	font-size: 30rpx;
	margin-bottom: 20rpx;
}

.card-number {
	font-size: 28rpx;
}

.untie {
	position: absolute;
	right: 30rpx;
	bottom: 30rpx;
	z-index: 3;
	color: #fff;
	font-size: 28rpx;
}

.btns {
	width: 667rpx;
	height: 102rpx;
	border: 1px dashed #d2d2d2;
	text-align: center;
	line-height: 100rpx;
	margin: 0 auto;
	color: #8d8d8d;
	font-size: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.add-icon {
	width: 33rpx;
	height: 33rpx;
	margin-right: 20rpx;
}

.tip {
	color: #8d8d8d;
	font-size: 30rpx;
	padding: 20rpx 30rpx;
}

/* uviewplus弹窗样式 */
.pay-dialog-content {
	padding: 40rpx 30rpx;
	text-align: center;
}

.pay-dialog-title {
	font-size: 36rpx;
	color: #333;
	margin-bottom: 30rpx;
	font-weight: 500;
}

.pay-dialog-body {
	padding: 20rpx 0;
}

.pay-tip {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 40rpx;
}
</style>